package com.athl.demoreactor.service.impl;

import com.athl.demoreactor.entity.User;
import com.athl.demoreactor.service.UserService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author hl
 * @Data 2020/9/16
 */
@Service
public class UserServiceImpl implements UserService {


    private final Map<Integer, User> map = new HashMap<>(50);

    public UserServiceImpl() {
        this.map.put(1, new User("lucy", "女", 20));
        this.map.put(2, new User("mike", "男", 21));
        this.map.put(3, new User("nick", "男", 23));
    }

    @Override
    public Mono<User> getUserById(int id) {
        User user = map.get(id);
        return Mono.just(user);
    }

    @Override
    public Flux<User> getAllUser() {
        return Flux.fromIterable(this.map.values());
    }

    @Override
    public Mono<Void> saveUserInfo(Mono<User> user) {
        return user.doOnNext(person -> {
            // 向map中取值
            int id = map.size() + 1;
            map.put(id, person);
        }).thenEmpty(Mono.empty());
    }
}
